<?php
header('Content-Type: text/plain');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = $_POST['action'];
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'save':
      save($myPdo);
      break;
    case 'del_image':
      del_image($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function save($myPdo) {
  if (!isset($_SESSION['admin' . USER])) {
    return;
  }
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  if (isset($q->id)) {
    DbUtils::update($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', $q);
  } else {
    $cond_vals = new stdClass();
    $cond_vals->c = 't.parent_id = :v1';
    $cond_vals->v = array(':v1' => $q->parent_id);
    $opt = new stdClass();
    $opt->select_expr = 'MAX(t.order) AS max';
    $q->order = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', $cond_vals, NULL, NULL, NULL, NULL, $opt)->d[0]->max + 1;
    DbUtils::add($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', $q);
    $q->id = $myPdo->lastInsertId();
  }
  echo json_encode($q);
}

function del_image($myPdo) {
  if (!isset($_SESSION['admin' . USER])) {
    return;
  }
  $q = MiscUtils::getParam('q', 0);
  
  //find userfile's id and path
  $cond_vals = new stdClass();
  $cond_vals->c = 't.id = :v1';
  $cond_vals->v = array(':v1' => $q);
  $tmp = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
  if (count($tmp) > 0) {
    $item = $tmp[0];
    //delete path
    $item->file = iconv('UTF-8', 'GB2312', $item->file);
    if (file_exists($item->file)) {
      @unlink($item->file);
    }
    //udpate brand
    $item->file = '';
    DbUtils::update($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', $item);
  }
  echo json_encode(array());
}
?>